package com.catering.common.seller.context;

import com.alibaba.ttl.TransmittableThreadLocal;

/**
 * 租户上下文持有人
 *
 * @author Administrator
 * @date 2023/02/24
 */
public class SellerContextHolder {

    /**
     * 当前租户编号
     */
    private static final ThreadLocal<Long> SELLER_ID = new TransmittableThreadLocal<>();

    /**
     * 是否忽略租户
     */
    private static final ThreadLocal<Boolean> IGNORE = new TransmittableThreadLocal<>();

    /**
     * 获得租户编号。
     *
     * @return 租户编号
     */
    public static Long getSellerId() {
        return SELLER_ID.get();
    }

    /**
     * 获得租户编号。如果不存在，则抛出 NullPointerException 异常
     *
     * @return 租户编号
     */
    public static Long getRequiredSellerId() {
        Long sellerId = getSellerId();
        if (sellerId == null) {
            throw new NullPointerException("SellerContextHolder 不存在店铺编号！");
        }
        return sellerId;
    }

    public static void setSellerId(Long sellerId) {
        SELLER_ID.set(sellerId);
    }

    public static void setIgnore(Boolean ignore) {
        IGNORE.set(ignore);
    }

    /**
     * 当前是否忽略租户
     *
     * @return 是否忽略
     */
    public static boolean isIgnore() {
        return Boolean.TRUE.equals(IGNORE.get());
    }

    public static void clear() {
        SELLER_ID.remove();
        IGNORE.remove();
    }

}
